#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "queue.h"

QUEUE* queue_new()
{
	QUEUE *queue;
	queue = (QUEUE*)malloc(sizeof(QUEUE));

	if(queue == NULL)
	{
		printf("No more memory!\n");
		return NULL;
	}

	queue->head=NULL;
	queue->tail=NULL;
	return queue;
}

int queue_add(QUEUE* queue ,char* data)
{
	if(queue == NULL)
		return -1;

	if(data == NULL)
		return -1;

	NODE* node = (NODE*)malloc(sizeof(NODE));
	if(node == NULL)
	{
		printf("NO MEMORY!\n");
		return -1;
	}

	node->data = (char*)malloc(strlen(data)+1);
	if(node->data == NULL)
	{
		printf("NO MEMORY!\n");
		return -1;
	}

	strcpy(node->data,data);
	node->next=NULL;

	if(queue->head == NULL)
	{
		queue->head=queue->tail=node;
		node->prev=NULL;
	}
	else
	{
		node->prev = queue->tail;
		queue->tail->next = node;
		queue->tail = node;
	}
	return 0;
}

char* queue_out(QUEUE* queue)
{
	if(queue == NULL)
		return NULL;
	if(queue->head == NULL)
		return NULL;
	char* data = queue->head->data;
	NODE *node = queue->head;
	queue->head = queue->head->next;
	if(queue->head != NULL)
	{
		queue->head->prev = NULL;
	}
	else
	{
		queue->tail = NULL;
	}
	free(node);
	return data;
}

void queue_removeall(QUEUE* queue)
{       
	NODE* tmp = queue->head;
	while(tmp != NULL)
	{   
		NODE* forfree = NULL;
		free(tmp->data);
		forfree = tmp;
		tmp = tmp->next;
		free(forfree);
	}
	queue->head = NULL;
	queue->tail = NULL;
	free(queue);
}
